import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:sonora/utils/sj_storage_utils.dart';

// import 'package:sonora/bloc/onboarding/sj_onboarding_bloc.dart';
// import 'package:sonora/bloc/onboarding/sj_onboarding_event.dart';
// import 'package:sonora/bloc/onboarding/sj_onboarding_state.dart';
import 'package:sonora/utils/sj_text_style.dart';
import 'package:sonora/views/appbar/sj_appbar.dart';
import 'package:sonora/views/navigation/routes/sj_app_router.dart';

@RoutePage()
class SjOnboardingPage extends StatefulWidget {
  const SjOnboardingPage({super.key});

  @override
  State<SjOnboardingPage> createState() => _SjOnboardingPageState();
}

class _SjOnboardingPageState extends State<SjOnboardingPage> {
  int pageCount = 3;
  int pageIndex = 0;
  bool isShowLaunchView = true;
  // SwiperController? _pagerController;

  final PageController _pageController = PageController();
  Timer? _autoNextPageTimer;
  static const int _autoNextPageDuration = 2; // 自动跳转时间（秒）
  int _currentPageIndex = 0;

  Timer? _autoSlideTimer;

  // void _cancelTimer() {
  //   _autoSlideTimer?.cancel();
  //   _autoSlideTimer = null;
  // }

  // void _startTimer() {
  //   _autoSlideTimer?.cancel();
  //   _autoSlideTimer = null;
  //   _autoSlideTimer = Timer.periodic(const Duration(seconds: 2), (Timer timer) {

  //       print('----------------------_startTimer pageIndex:$pageIndex');
  //       _nextPage();
  //       }
  //   );
  // }

  // void _resetTimer() {
  //   _cancelTimer();
  //   _autoSlideTimer = Timer(const Duration(seconds: 2), () {

  //       print('----------------------_resetTimer pageIndex:$pageIndex');
  //     if (pageIndex == pageCount - 1) _nextPage();
  //   });
  // }

  // Future<void> _nextPage() async {
  //   _pagerController?.next();
  // }

  // void _loginPage() async {
  //   _cancelTimer();
  //   context.router.replace(const SjLoginRoute());
  // }

  // @override
  // void initState() {
  //   _pagerController = SwiperController();
  //   super.initState();

  //   // () async {
  //   //   bool firstLaunch = await SjStorageUtils.getAppFirstLaunch();
  //   //   // if (kDebugMode) firstLaunch = true;
  //   //   if (firstLaunch) {
  //   //     isShowLaunchView = false;
  //   //     setState(() {});
  //   //     SjStorageUtils.saveAppFirstLaunch();
  //       // _startTimer();
  //   //   } else {
  //   //     await Future.delayed(const Duration(seconds: 2));
  //   //     _loginPage();
  //   //   }
  //   // }();
  // }

  // @override
  // void dispose() {
  //   _pagerController?.dispose();
  //   _pagerController = null;
  //   super.dispose();
  // }

  @override
  void initState() {
    SjStorageUtils.saveAppFirstLaunch();
    // 隐藏状态栏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky,
        overlays: []);
    _startAutoNextPageTimer();
    super.initState();
  }

  void _startAutoNextPageTimer() {
    _autoNextPageTimer?.cancel();
    _autoNextPageTimer = Timer.periodic(
        const Duration(seconds: _autoNextPageDuration), (Timer timer) {
      _nextPage();
    });
  }

  void _nextPage() {
    if (_currentPageIndex < pageCount - 1) {
      // 假设有 3 页引导页
      _pageController.nextPage(
        duration: Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    } else {
      // 自动跳转到登录页的逻辑已经被移除
      // 在最后一页时不自动跳转
    _autoNextPageTimer?.cancel();
      context.router.pushAndPopUntil(
        const SjLoginRoute(),
        predicate: (route) => false, // 清空栈
      );
    }
  }

  void _clickNextStartAutoNextPageTimer() {
    _autoNextPageTimer?.cancel();
    if (_currentPageIndex < pageCount - 1) {
      // 假设有 3 页引导页
      _pageController.nextPage(
        duration: Duration(milliseconds: 0),
        curve: Curves.easeInOut,
      );
    }
    _startAutoNextPageTimer();
  }

  void _onPageChanged(int index) {
    setState(() {
      _currentPageIndex = index;
      _startAutoNextPageTimer(); // 重新启动计时器
    });
  }

  @override
  void dispose() {
    _autoNextPageTimer?.cancel();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(body: _pagerView());

  Widget _launchView() {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
            fit: BoxFit.fill, image: AssetImage('assets/images/launch.png')),
      ),
      child: Center(
        child: Column(
          children: [
            SizedBox(height: MediaQuery.of(context).padding.top + 145),
            Image.asset('assets/images/logo.png', width: 100),
            const SizedBox(height: 15),
            const Text('Sona', style: SjTextStyle.customFontWhite24),
          ],
        ),
      ),
    );
  }

  Widget _pagerView() {
    return PageView.builder(
      itemCount: pageCount,
      controller: _pageController,
      onPageChanged: _onPageChanged,
      itemBuilder: (BuildContext context, int index) {
        Widget _backgroundView(int index) {
          Widget w;
          Widget image = Image.asset('assets/images/guide_${index + 1}.png',
              fit: BoxFit.fitWidth);
          w = image;
          return w;
        }

        // return _backgroundView(index);
        return Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Positioned(
                top: 0,
                bottom: 0,
                left: 0,
                right: 0,
                child: _backgroundView(index)),
            Positioned(
              top: 40,
              right: 10,
              child: IconButton(
                onPressed: () {
                  if (index < 2) {
                    _clickNextStartAutoNextPageTimer();
                  } else {
                    context.router.pushAndPopUntil(
                      const SjLoginRoute(),
                      predicate: (route) => false, // 清空栈
                    );
                  }
                },
                icon: index != 2
                    ? Image.asset(
                        'assets/images/guide_next_btn.png',
                        width: 30,
                      )
                    : Image.asset(
                        'assets/images/guide_go_btn.png',
                        width: 30,
                      ),
              ),
            ),
            _bottomText(index),
          ],
        );
      },
    );
  }

  Widget _bottomText(int index) {
    const text1 = 'Explore handpan melodies and\n connect globally.';
    const text2 = "Find tutorials, share performances,\n and learn.";
    const text3 = 'Follow trends, events, and\n innovations.';
    final text = index == 0 ? text1 : (index == 1 ? text2 : text3);
    return Positioned(
      bottom: 36,
      child: Text(text, style: SjTextStyle.customFontWhite24, maxLines: 2),
    );
  }
}
